﻿// -------------------------------------------------------------------------------------------------------------------------------
// <copyright file="CrcsSparseMatrixExtensions.cs" company="Exul">
//     Copyright (c) Exul. All rights reserved.
// </copyright>
// <author>
//     Exul
// </author>
// -------------------------------------------------------------------------------------------------------------------------------

namespace ExulLibrary.Mathematics.LinearAlgebra.Sequential
{
    #region Usings

    using System;

    using ExulLibrary.Exceptions;
    using ExulLibrary.Mathematics.LinearAlgebra.Exceptions;

    #endregion

    /// <summary>
    ///     Provides extension methods for <see cref="CrcsSparseMatrix{T}"/>.
    /// </summary>
    public static class CrcsSparseMatrixExtensions
    {
        #region Methods

        #region public

        /// <summary>
        ///     Sets the default value to all elements of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains elements to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        public static void Clear<T>(this CrcsSparseMatrix<T> matrix)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            #endif

            Array.Clear(matrix.DiagonalValues, 0, Math.Min(matrix.RowsCount, matrix.ColumnsCount));
            Array.Clear(
                matrix.LowTriangleValues,
                matrix.LowTriangleRowsBegins[0],
                matrix.LowTriangleRowsBegins[matrix.RowsCount] - matrix.LowTriangleRowsBegins[0]);
            Array.Clear(
                matrix.HighTriangleValues,
                matrix.HighTriangleColumnsBegins[0],
                matrix.HighTriangleColumnsBegins[matrix.ColumnsCount] - matrix.HighTriangleColumnsBegins[0]);
        }

        /// <summary>
        ///     Sets the default value to all elements in the specified column of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the column to clear.
        /// </param>
        /// <param name="columnIndex">
        ///     The zero-based index of the column to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="columnIndex"/> is negative or greater than or equal to columns count.
        /// </exception>
        public static void ClearColumn<T>(this CrcsSparseMatrix<T> matrix, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            // clear high triangle values
            Array.Clear(
                matrix.HighTriangleValues,
                matrix.HighTriangleColumnsBegins[columnIndex],
                matrix.HighTriangleColumnsBegins[columnIndex + 1] - matrix.HighTriangleColumnsBegins[columnIndex]);

            if (matrix.RowsCount <= columnIndex)
            {
                return;
            }

            // clear diagonal element
            matrix.DiagonalValues[columnIndex] = default(T);

            var rowsBegins = matrix.LowTriangleRowsBegins;
            var columnsIndexes = matrix.LowTriangleColumnsIndexes;
            var values = matrix.LowTriangleValues;

            var rowEnd = rowsBegins[columnIndex + 1];

            var rowsCount = matrix.RowsCount;
            for (var rowIndex = columnIndex + 1; rowIndex < rowsCount; rowIndex++)
            {
                var elementIndex = rowEnd;
                rowEnd = rowsBegins[rowIndex + 1];
                while ((rowIndex < rowEnd) && (columnsIndexes[elementIndex] < columnIndex))
                {
                    elementIndex++;
                }

                if ((elementIndex < rowEnd) && (columnsIndexes[elementIndex] == columnIndex))
                {
                    // clear low triangle values
                    values[elementIndex] = default(T);
                }
            }
        }

        /// <summary>
        ///     Sets the default value to all elements in the specified row of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the row to clear.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of the row to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to rows count.
        /// </exception>
        public static void ClearRow<T>(this CrcsSparseMatrix<T> matrix, int rowIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            #endif

            // clear low triangle values
            Array.Clear(
                matrix.LowTriangleValues,
                matrix.LowTriangleRowsBegins[rowIndex],
                matrix.LowTriangleRowsBegins[rowIndex + 1] - matrix.LowTriangleRowsBegins[rowIndex]);

            if (matrix.ColumnsCount <= rowIndex)
            {
                return;
            }

            // clear diagonal element
            matrix.DiagonalValues[rowIndex] = default(T);

            var columnsBegins = matrix.HighTriangleColumnsBegins;
            var rowsIndexes = matrix.HighTriangleRowsIndexes;
            var values = matrix.HighTriangleValues;

            var columnEnd = columnsBegins[rowIndex + 1];

            var columnsCount = matrix.ColumnsCount;
            for (var columnIndex = rowIndex + 1; columnIndex < columnsCount; columnIndex++)
            {
                var elementIndex = columnEnd;
                columnEnd = columnsBegins[columnIndex + 1];
                while ((elementIndex < columnEnd) && (rowsIndexes[elementIndex] < rowIndex))
                {
                    elementIndex++;
                }

                if ((elementIndex < columnEnd) && (rowsIndexes[elementIndex] == rowIndex))
                {
                    // clear high triangle values
                    values[elementIndex] = default(T);
                }
            }
        }

        /// <summary>
        ///     Creates a deep copy of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="source">
        ///     The source matrix.
        /// </param>
        /// <returns>
        ///     A deep copy of the matrix.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="source"/> is <see langword="null"/>.
        /// </exception>
        /// <remarks>
        ///     This methods doesn't create a deep copy for collections of rows/columns begins and indexes.
        /// </remarks>
        public static CrcsSparseMatrix<T> Clone<T>(this CrcsSparseMatrix<T> source)
        {
            #if SAFE

            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            #endif

            var result = new CrcsSparseMatrix<T>(
                source.LowTriangleRowsBegins,
                source.LowTriangleColumnsIndexes,
                source.HighTriangleColumnsBegins,
                source.HighTriangleRowsIndexes);
            Array.Copy(source.LowTriangleValues, result.LowTriangleValues, result.LowTriangleValues.Length);
            Array.Copy(source.DiagonalValues, result.DiagonalValues, result.DiagonalValues.Length);
            Array.Copy(source.HighTriangleValues, result.HighTriangleValues, result.HighTriangleValues.Length);
            return result;
        }

        /// <summary>
        ///     Gets the element in the matrix at the specified location.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the element to get.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of row of the element to get.
        /// </param>
        /// <param name="columnIndex">
        ///     The zero-based index of column of the element to get.
        /// </param>
        /// <returns>
        ///     The element in the matrix at the specified location.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to
        ///     the number of rows of <paramref name="matrix"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="columnIndex"/> is negative or greater than or equal to
        ///         the number of columns of <paramref name="matrix"/>.
        ///     </para>
        /// </exception>
        public static T GetAt<T>(this CrcsSparseMatrix<T> matrix, int rowIndex, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            if (rowIndex == columnIndex)
            {
                return matrix.DiagonalValues[rowIndex];
            }

            if (columnIndex < rowIndex)
            {
                var columnsIndexes = matrix.LowTriangleColumnsIndexes;

                var elementRowIndex = matrix.LowTriangleRowsBegins[rowIndex];
                var rowEnd = matrix.LowTriangleRowsBegins[rowIndex + 1];
                while ((elementRowIndex < rowEnd) && (columnsIndexes[elementRowIndex] < columnIndex))
                {
                    elementRowIndex++;
                }

                return (elementRowIndex == rowEnd) || (columnsIndexes[elementRowIndex] != columnIndex)
                           ? default(T)
                           : matrix.LowTriangleValues[elementRowIndex];
            }

            var rowsIndexes = matrix.HighTriangleRowsIndexes;

            var elementColumnIndex = matrix.HighTriangleColumnsBegins[columnIndex];
            var columnEnd = matrix.HighTriangleColumnsBegins[columnIndex + 1];
            while ((elementColumnIndex < columnEnd) && (rowsIndexes[elementColumnIndex] < rowIndex))
            {
                elementColumnIndex++;
            }

            return (elementColumnIndex == columnEnd) || (rowsIndexes[elementColumnIndex] != rowIndex)
                       ? default(T)
                       : matrix.HighTriangleValues[elementColumnIndex];
        }

        /// <summary>
        ///     Sets the element in the matrix at the specified location.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the element to set.
        /// </param>
        /// <param name="newValue">
        ///     The new value for the element.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of row of the element to set.
        /// </param>
        /// <param name="columnIndex">
        ///     The zero-based index of column of the element to set.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to
        ///     the number of rows of <paramref name="matrix"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="columnIndex"/> is negative or greater than or equal to
        ///         the number of columns of <paramref name="matrix"/>.
        ///     </para>
        /// </exception>
        /// <exception cref="ReadOnlyMatrixElementException">
        ///     <paramref name="rowIndex"/> and <paramref name="columnIndex"/> specifies the element
        ///     that is not in the portrait of <paramref name="matrix"/>.
        /// </exception>
        public static void SetAt<T>(this CrcsSparseMatrix<T> matrix, T newValue, int rowIndex, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            if (rowIndex == columnIndex)
            {
                matrix.DiagonalValues[rowIndex] = newValue;

                return;
            }

            if (columnIndex < rowIndex)
            {
                var columnsIndexes = matrix.LowTriangleColumnsIndexes;

                var elementRowIndex = matrix.LowTriangleRowsBegins[rowIndex];
                var rowEnd = matrix.LowTriangleRowsBegins[rowIndex + 1];
                while ((elementRowIndex < rowEnd) && (columnsIndexes[elementRowIndex] < columnIndex))
                {
                    elementRowIndex++;
                }

                // if element is not found, skip it
                if ((elementRowIndex == rowEnd) || (columnsIndexes[elementRowIndex] != columnIndex))
                {
                    #if SAFE

                    throw new ReadOnlyMatrixElementException("matrix", rowIndex, columnIndex);

                    #else

                    return;

                    #endif
                }

                matrix.LowTriangleValues[elementRowIndex] = newValue;

                return;
            }

            var rowsIndexes = matrix.HighTriangleRowsIndexes;

            var elementColumnIndex = matrix.HighTriangleColumnsBegins[columnIndex];
            var columnEnd = matrix.HighTriangleColumnsBegins[columnIndex + 1];
            while ((elementColumnIndex < columnEnd) && (rowsIndexes[elementColumnIndex] < rowIndex))
            {
                elementColumnIndex++;
            }

            // if element is not found, skip it
            if ((elementColumnIndex == columnEnd) || (rowsIndexes[elementColumnIndex] != rowIndex))
            {
                #if SAFE

                throw new ReadOnlyMatrixElementException("matrix", rowIndex, columnIndex);

                #else

                return;

                #endif
            }

            matrix.HighTriangleValues[elementColumnIndex] = newValue;
        }

        #endregion

        #endregion
    }
}